package org.dev.`as`.project.common.flutter

import android.content.Context
import io.flutter.embedding.engine.loader.FlutterLoader
import java.io.File
import java.lang.Exception

/**
 * Author WenPing
 * CreateTime 2021/10/10.
 * Description:
 *
 * 利用反射将新的Flutter的代码so，注入到Flutter的so的加载流程中
 * Flutter 1.18或以下版本支持热修复，详见说明：https://class.imooc.com/course/qadetail/262865
 */
class HiFlutterLoader : FlutterLoader() {

    /**
     * 创建静态实例
     */
    companion object {
        const val FIX_SO = "libappfix.so"
        private var instance: HiFlutterLoader? = null
            get() {
                if (field == null) {
                    field == HiFlutterLoader()
                }
                return field
            }

        fun get(): HiFlutterLoader {
            return instance!!
        }
    }

    /**
     * 根据反射,将本地so文件的路径替换到FlutterLoader的so路径中
     */
    override fun ensureInitializationComplete(
        applicationContext: Context,
        args: Array<out String>?
    ) {
        val path = applicationContext.filesDir
        val soFile = File(path, FIX_SO)
        // 如果so文件存在
        if (soFile.exists()) {
            try {
                val field = FlutterLoader::class.java.getDeclaredField("aotSharedLibraryName")
                field.isAccessible = true
                // field中的so路径替换成 新的so的路径
                field[this] = soFile.absolutePath
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        //在FlutterJNI.nativeInit之前将so路径替换好
        super.ensureInitializationComplete(applicationContext, args)
    }

}